import requests
from bs4 import BeautifulSoup
import time

# 发送请求, 获取页面源代码
domain = "https://www.umei.cc/weimeitupian/wenzitupian/"
head = {
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36"
}

resp = requests.get(domain, headers=head)
resp.encoding = "utf-8"

# 使用BeautifulSoup 进行解析, 返回bs 对象
main_page = BeautifulSoup(resp.text, "html.parser")
# 从bs 对象中找出所有照片的子页面a 标签
alist = main_page.find("div", attrs={"class": "item_list infinite_scroll"}).find_all("a")[::3]

for a in alist:
    # 获取子页面中的图片链接
    link = domain + a.get("href")[-10:]  # get() 函数可以直接获取标签属性值
    child_resp = requests.get(link, headers=head)
    child_resp.encoding = "utf-8"

    # bs 解析
    child_page = BeautifulSoup(child_resp.text, "html.parser")

    # 图片链接
    img_link = child_page.find("div", attrs={"class": "big-pic"}).find("img")
    src = img_link.get("src")

    # 下载图片
    img_resp = requests.get(src)
    img_name = src.split("/")[-1]  # 拿到url 中最后一部分做图片名
    with open("img/" + img_name, mode="wb") as f:
        f.write(img_resp.content)  # 图片内容写入文件

    print("over " + img_name)
    time.sleep(3)

resp.close()
print("all over")
